import Vue from 'vue'
import VueRouter from 'vue-router'
const Home = () => import('../components/Home.vue')
const Login = () => import('../components/Login.vue')
const Order = () => import('../components/Order.vue')
const Case = () => import('../components/Case.vue')
const Company = () => import('../components/Company.vue')
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Login',
    component: Login,
  },
  {
    path: '/home',
    name: 'Home',
    component: Home,
  },
  {
    path: '/order',
    name: 'Order',
    component: Order,
  },
  {
    path: '/case',
    name: 'Case',
    component: Case,
  },
  {
    path: '/company',
    name: 'Company',
    component: Company,
  },
]

const router = new VueRouter({
  routes,
})

//避免重复点击当前页面的路径提示异常，不影响程序的正常执行
const VueRouterPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(to) {
  return VueRouterPush.call(this, to).catch((err) => err)
}

function getTitle(path) {
  switch (path) {
    case '/home': {
      return '首页'
    }
    case '/': {
      return '登录'
    }
    case '/case': {
      return '案例'
    }
    case '/company': {
      return '公司'
    }
    case '/order': {
      return '预约'
    }
  }
}

router.beforeEach((to, from, next) => {
  console.log('from:' + from.path)
  document.title = getTitle(to.path)
  //1、拦截登录
  if (to.path === '/') {
    return next()
  }
  //2、获得登录信息
  let str = sessionStorage.getItem('login_user')
  if (!str) {
    return next('/')
  }
  let user = JSON.parse(str)
  if (!user.data) {
    return next('/')
  }
  if (!user.data.user) {
    return next('/')
  }
  if (!user.data.user.name) {
    return next('/')
  }
  //放行
  next()
})

export default router
